//
//  OAuthViewController.swift
//  新浪微博
//
//  Created by 李赛 on 15/5/12.
//  Copyright (c) 2015年 李赛. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController,UIWebViewDelegate {
    @IBOutlet weak var webView: UIWebView!
    /**
    App Key：894262198
    App Secret：122542ac423e272622cd73c9f6007602
    http://github.com/StackLi
    */
    
    let client_id = "894262198"
    let client_secret = "122542ac423e272622cd73c9f6007602"
    let redirect_uri = "http://github.com/StackLi"
    
    // 关闭modal出来的窗口
    @IBAction func close() {    
        dismissViewControllerAnimated(true, completion: nil)
        SVProgressHUD.dismiss()
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        // 加载授权页面
        loadAuthPage()
    }

    // 加载授权页面
    private func loadAuthPage(){
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        println(urlString)
        SVProgressHUD.show()
        webView.loadRequest(NSURLRequest(URL: NSURL(string: urlString)!))
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //MARK - webView代理方法
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL!.absoluteString!
        if urlString.hasPrefix("https://api.weibo.com/"){
            return true
        }
        if urlString.hasPrefix(redirect_uri){
            println(request.URL?.query)
        }
        let codeStr = "code="
        let query = request.URL!.query!
        if query.hasPrefix(codeStr){
            let code = (query as NSString).substringFromIndex(codeStr.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
            println("验证码" + code)
            loadAccessToken(code)
            
        }else{
            println("用户拒绝")
            close()
        }
        
        return false
    }
    
    //
    private func loadAccessToken(code:String){
        let params = ["client_id":client_id,
            "client_secret":client_secret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":redirect_uri
        ]
        UserAccount.loadAccessToken(params, completion: { (account) -> () in
            if account != nil {
                // 设置全局变量
                sharedUserAccount = account
                
                // 发送通知前往欢迎界面
                println("发送通知,前往欢迎界面")
                NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootViewControllerNotification, object: "Welcome")
                // 关闭modal出来的窗口
                self.close()
                
                return
            }
            SVProgressHUD.showErrorWithStatus("您的网络不给力啊")
        })
    }
    
    // 设置加载动画
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
}
